package com.admin.service;

import com.admin.model.ActivationCode;
import com.admin.repository.mongo.ActivationCodeRepository;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class EhCacheService implements InitializingBean {

    private CacheManager cacheManager;
    private Cache validateCache;

    @Resource
    private ActivationCodeRepository activationCodeRepository;

    /**
     * 序列list
     */
    private final List<String> sequenceList = new ArrayList<>();
    /**
     * 激活码list
     */
    private final List<String> codeList = new ArrayList<>();

    public List<String> getSequenceList() {
        return sequenceList;
    }

    public List<String> getCodeList() {
        return codeList;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        cacheManager = CacheManager.create(new ClassPathResource("ehcache.xml").getInputStream());
        validateCache = cacheManager.getCache("validate-code");
        List<ActivationCode> all = activationCodeRepository.findAll();
        for (ActivationCode activationCode : all) {
            sequenceList.add(activationCode.getSequence());
            codeList.add(activationCode.getCode());
        }
    }

    /**
     * 添加验证码缓存
     *
     * @param key
     * @param code
     * @param version 0:注册   1:忘记密码
     */
    public void setValidateCode(String key, String code) {
        Element element = new Element(key, code);
        validateCache.put(element);
    }

    /**
     * 通过手机号取出验证码缓存
     *
     * @param key
     * @return
     */
    public String getValidateCode(String key) {
        Element element = validateCache.get(key);
        Object value = element.getObjectValue();
        return value == null ? null : value.toString();
    }
}
